<template>
  <div class="log-management">    
    <!-- 查询条件区域 -->
    <div class="search-container">
      <el-form :model="queryParams" ref="queryForm" :inline="true">
        <el-form-item label="时间范围" prop="dateRange">
          <el-date-picker
            v-model="queryParams.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        
        <el-form-item label="用户名称" prop="userName">
          <el-input
            v-model="queryParams.userName"
            placeholder="请输入用户名称"
            clearable
          />
        </el-form-item>
        
        <el-form-item label="操作类型" prop="action">
          <el-select
            v-model="queryParams.action"
            placeholder="请选择操作类型"
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="item in actionTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <!-- 调试信息 -->
          <div style="font-size: 12px; color: #999; margin-top: 4px;">
            当前选中: {{ queryParams.action === '' ? '全部' : queryParams.action }}
          </div>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleQuery">搜索</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <!-- 操作按钮区域 -->
    <div class="operation-container">
      <el-button
        type="success"
        :loading="exportLoading"
        @click="handleExport"
      >
        导出日志
      </el-button>
    </div>
    
    <!-- 日志列表区域 -->
    <div class="log-table">
      <el-table
        :data="logList"
        border
        v-loading="loading"
        style="width: 100%"
      >
        <!-- <el-table-column prop="id" label="日志ID" width="180" /> -->
        <!-- <el-table-column prop="userId" label="用户ID" width="180" /> -->
        <el-table-column prop="serialNumber" label="序号" width="80">
          <template #default="{ row }">
            {{ row.serialNumber || '--' }}
          </template>
        </el-table-column>

        <el-table-column prop="userName" label="用户名称" width="150">
          <template #default="{ row }">
            {{ row.userName || '无' }}
          </template>
        </el-table-column>

        <el-table-column prop="action" label="操作类型" width="150">
          <template #default="{ row }">
            <el-tag :type="getActionTypeTag(row.action)">
              {{ formatAction(row.action) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="formattedResource" label="操作内容" width="300">
          <template #default="{ row }">
            {{ row.formattedResource || row.resource || '--' }}
          </template>
        </el-table-column>
        
        <el-table-column prop="resourceId" label="资源ID" width="180" />
        <el-table-column prop="createdAt" label="操作时间" width="180">
          <template #default="{ row }">
            {{ formatTime(row.createdAt) }}
          </template>
        </el-table-column>
      </el-table>
      
      <el-pagination
        v-model:current-page="queryParams.pageIndex"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="getList"
        @current-change="getList"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { logApi } from '../../api/log'
import { downloadFile } from '@/utils/request'
import dayjs from 'dayjs'

// 加载状态
const loading = ref(false)
const exportLoading = ref(false)

// 日志列表数据
const logList = ref([])
const total = ref(0)

// 操作类型选项 - 根据后端实际返回数据更新
const actionTypes = [
  { value: '', label: '全部' },
  { value: 'UserCreated', label: '用户创建' },
  { value: 'Create', label: '创建' },
  { value: 'Update', label: '更新' },
  { value: 'UserUpdated', label: '用户更新' },
  { value: 'Delete', label: '删除' },
  { value: 'UserDeleted', label: '用户删除' },
  { value: 'Query', label: '查询' },
  { value: 'QueryList', label: '查询列表' },
  { value: 'QueryByUsername', label: '按用户名查询' },
  { value: 'QueryByUsernameFuzzy', label: '模糊查询' },
  { value: 'QueryUserRoles', label: '查询用户角色' },
  { value: 'AssignRole', label: '分配角色' },
  { value: 'RemoveRole', label: '移除角色' },
  { value: 'Enable', label: '启用' },
  { value: 'Disable', label: '禁用' },
  { value: 'Login', label: '用户登录' },
  { value: 'Logout', label: '用户登出' }
]

// 查询参数
const queryParams = reactive({
  pageIndex: 1,
  pageSize: 10,
  action: '',
  userName: '',
  dateRange: []
})

// 监控action值变化
import { watch } from 'vue'
watch(() => queryParams.action, (newValue) => {
  console.log('操作类型变化:', newValue)
})

const queryForm = ref(null)

// 获取日志列表
const getList = async () => {
  loading.value = true
  
  try {
    // 构造请求参数 - 确保格式与后端一致
    const params = {
      pageIndex: queryParams.pageIndex,
      pageSize: queryParams.pageSize,
      action: queryParams.action,
      userName: queryParams.userName || undefined // 不传空字符串
    }
    
    // 处理日期范围
    if (queryParams.dateRange?.length === 2) {
      params.startTime = `${queryParams.dateRange[0]}T00:00:00Z`
      params.endTime = `${queryParams.dateRange[1]}T23:59:59Z`
    }
    
    const response = await logApi.queryLog(params)
    console.log('接口返回数据:', response.items) 
    // 根据后端返回结构调整
    logList.value = response.items || []
    total.value = response.total || 0
  } catch (error) {
    console.error('获取日志列表失败:', error)
    ElMessage.error('获取日志列表失败')
  } finally {
    loading.value = false
  }
}

// 处理查询
const handleQuery = () => {
  queryParams.pageIndex = 1
  getList()
}

// 重置查询
const resetQuery = () => {
  queryForm.value?.resetFields()
  queryParams.action = ''
  queryParams.userName = ''
  queryParams.dateRange = []
  handleQuery()
}

// 导出日志
const handleExport = async () => {
  exportLoading.value = true
  try {
    console.log('开始导出日志...')
    
    // 构造导出参数
    const params = {
      pageIndex: 1,
      pageSize: total.value, // 导出所有数据
      action: queryParams.action,
      userName: queryParams.userName || undefined
    }
    
    // 处理日期范围
    if (queryParams.dateRange?.length === 2) {
      params.startTime = `${queryParams.dateRange[0]}T00:00:00Z`
      params.endTime = `${queryParams.dateRange[1]}T23:59:59Z`
    }
    
    console.log('导出参数:', params)
    console.log('调用API...')
    
    const response = await logApi.exportLog(params)
    
    console.log('API响应:', response)
    console.log('响应类型:', typeof response)
    console.log('响应大小:', response?.size || response?.length)
    
    // 检查响应是否为空
    if (!response) {
      throw new Error('响应为空')
    }
    
    // 创建下载链接
    const blob = new Blob([response], { type: 'text/csv; charset=utf-8' })
    console.log('Blob大小:', blob.size)
    
    if (blob.size === 0) {
      throw new Error('Blob大小为0，没有数据')
    }
    
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `操作日志_${dayjs().format('YYYY-MM-DD')}.csv`
    
    console.log('创建下载链接:', link.href)
    console.log('文件名:', link.download)
    
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    console.log('下载完成')
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出日志失败:', error)
    console.error('错误详情:', error.response)
    ElMessage.error(`导出日志失败: ${error.message}`)
  } finally {
    exportLoading.value = false
  }
}

// 格式化操作类型显示 - 更新操作类型映射
const formatAction = (action) => {
  const actionMap = {
    'UserCreated': '用户创建',
    'Create': '创建',
    'Update': '更新',
    'UserUpdated': '用户更新',
    'Delete': '删除',
    'UserDeleted': '用户删除',
    'Query': '查询',
    'QueryList': '查询列表',
    'QueryByUsername': '按用户名查询',
    'QueryByUsernameFuzzy': '模糊查询',
    'QueryUserRoles': '查询用户角色',
    'AssignRole': '分配角色',
    'RemoveRole': '移除角色',
    'Enable': '启用',
    'Disable': '禁用',
    'Login': '用户登录',
    'Logout': '用户登出'
  }
  return actionMap[action] || action
}

// 获取操作类型标签样式 - 更新标签类型映射
const getActionTypeTag = (action) => {
  const typeMap = {
    'UserCreated': 'success',
    'Create': 'success',
    'Update': 'warning',
    'UserUpdated': 'warning',
    'Delete': 'danger',
    'UserDeleted': 'danger',
    'Query': 'primary',
    'QueryList': 'primary',
    'QueryByUsername': 'primary',
    'QueryByUsernameFuzzy': 'primary',
    'QueryUserRoles': 'primary',
    'AssignRole': 'success',
    'RemoveRole': 'danger',
    'Enable': 'success',
    'Disable': 'warning',
    'Login': 'primary',
    'Logout': 'info'
  }
  return typeMap[action] || ''
}

// 修复日期时间格式化函数
const formatTime = (time) => {
  if (!time) return '--'
  const date = new Date(time)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  }).replace(/\//g, '-')
}

// 初始化加载数据
onMounted(() => {
  getList()
})
</script>

<style scoped>
.log-management {
  padding: 20px;
}

.header {
  margin-bottom: 20px;
}

.search-container {
  background: #f5f7fa;
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 4px;
}

.operation-container {
  margin-bottom: 20px;
}

.log-table {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
}
</style>